package com.yscp.ysdemo.handler;

import com.alibaba.fastjson.JSON;
import com.yscp.ysdemo.constant.ResultEnum;
import com.yscp.ysdemo.dto.ResponseResult;
import com.yscp.ysdemo.exception.BusinessException;
import io.netty.util.internal.logging.Log4J2LoggerFactory;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
@RestControllerAdvice
public class ExceptionHandle {

    private final static Logger logger= LoggerFactory.getLogger(ExceptionHandler.class);
    /**
     * 顶层业务异常处理，包装成正常信息返回
     * @param e
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ExceptionHandler({BusinessException.class})
    public ResponseResult solveBusinessException(BusinessException e, HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.error("业务异常："+e.getMessage(),e);
        return ResponseResult.error(e.getCode(),e.getMessage());
    }




    /**
     * 系统异常处理
     * @param e
     * @param request
     * @param response
     * @throws Exception
     */
    @ExceptionHandler({Exception.class})
    public ResponseResult solveException(Exception e, HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.error("系统异常："+e.getMessage(),e);
        return  ResponseResult.error(ResultEnum.SYSTEM_ERROR.getCode(),ResultEnum.SYSTEM_ERROR.getMsg());
    }
}
